package com.nzx.config;

import com.nzx.common.annotation.LoginRequired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * 类描述：web处理拦截器
 *
 * @author niezhuxe
 * @date 2020/11/11 10:20
 */
@Slf4j
@Component
public class WebInterceptor implements HandlerInterceptor {

    /**
     * 重写handler处理器，在handler之前做处理操作
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前访问路径
        String url = request.getRequestURI();
        log.info(">>>>> 当前[{}]访问路径信息url:{}", LocalDateTime.now(),url);

        //为不需要登录的接口配置-免除登录
        if(handler instanceof HandlerMethod){
            //获取对应的方法处理器对象
            HandlerMethod hm = (HandlerMethod)handler;
            //根据注解类型 获取方法处理器中的注解对象
            LoginRequired loginRequired = hm.getMethodAnnotation(LoginRequired.class);
            if(loginRequired != null){
                if(loginRequired.unLoginCanAccess()){
                    return true;
                }
            }
        }
        return true;
    }
}
